<template>
  <section class="todoapp">
    <ToduHeader @add="addTodo"></ToduHeader>
    <ToduMain
      :list="list2"
      @del="handDel"
      @state="handSate"
      @AllState="handAllState"
    ></ToduMain>
    <ToduFooter
      :list="list"
      @clearCompleted="handlclear"
      :flag="flag"
      @changeFlag="changeFlag"
    ></ToduFooter>
  </section>
</template>

<script>
import ToduFooter from "@/components/ToduFooter.vue";
import ToduMain from "@/components/ToduMain.vue";
import ToduHeader from "@/components/ToduHeader.vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todo-list")),
      // list: [
      //   // isDone: 是否完成
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      flag: "1",
    };
  },
  components: {
    ToduFooter,
    ToduMain,
    ToduHeader,
  },
  methods: {
    handDel(id) {
      this.list = this.list.filter((item) => item.id != id);
    },
    addTodo(todo) {
      // 数组.push向数组结尾插入数据   数组.unshift 向数组开头插入数据
      //接收到头部组件数据后,添加数据
      this.list.push({
        id: Date.now(),
        name: todo,
        isDone: false,
      });
    },
    handSate(id) {
      console.log(id);
    },
    handlclear() {
      //保留未完成的
      this.list = this.list.filter((item) => item.isDone === false);
    },
    changeFlag(flag) {
      //将子组件传来的状态赋值给控制显示内容类别的标记上
      this.flag = flag;
    },
    handAllState(boo) {
      //控制全选状态
      this.list.forEach((item) => {
        item.isDone = boo;
      });
    },
  },

  computed: {
    list2() {
      //数据根据flag标记的变化而变化
      if (this.flag === 3) {
        return this.list.filter((item) => item.isDone === false);
      } else if (this.flag === 2) {
        return this.list.filter((item) => item.isDone === true);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      handler(newVal) {
        console.log(newVal);
        //数组发生改变将改变后得数据添加到本地存储中
        localStorage.setItem("todo-list", JSON.stringify(newVal));
      },
      immediate: true, //立即侦听
      deep: true, //深度侦听，侦听对象内部得属性变化
    },
  },
};
</script>

<style></style>
